<?php
namespace app\index\controller;
use think\Config;
use think\response\Json;
use think\Session;

class Ajax{

    protected $api_url;
    protected $api_key;

    function __construct(){
        if($_SERVER['REQUEST_METHOD'] != 'POST'){
            exit('illegal request.');
        }
        $this->api_url = Config::get('api_url');
        $this->api_key = Config::get('api_key');
    }

    /**
     * 检测并返回数据
     * @param $params
     * @return array|string
     */
    protected function check(array $params){
        $post = input();
        $data = array();
        foreach($params as $item){
            if(isset($post[$item])){
                $data[$item] = $post[$item];
            }else{
                $this->dump("missing parameter {$item}!");
            }
        }
        return $data;
    }

    /**
     * 输出json数据
     * @param $msg
     * @param int $status
     * @param array $data
     * @return string
     */
    protected function dump($msg, $status = 2, $data = array()){
        exit(json_encode(array('status'=>$status, 'msg'=>$msg, 'data'=>$data)));
    }

    /**
     * 请求数据
     * @param $action
     * @param array $params
     * @param string $type
     * @param $upload
     * @return mixed
     */
    protected function connect($action, $params = array(), $type = 'POST', $upload = false){
        $data = array();
        $method = strtoupper($type);
        $url = $this->api_url . $action;
        $params['api_key'] = $this->api_key;
        if($method == 'GET'){
            $url = "{$url}?" . http_build_query($params);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        if($method == 'POST'){
            if($upload){        //设置上传文件
                $file = new \CURLFile($upload['file'], $upload['type'], $upload['name']);
                $params[$upload['get_name']] = $file;
            }
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        }
        $result = curl_exec($ch);
        curl_close($ch);
        if($data === null){
            $this->dump('请求数据失败.', 2);
        }else{
            try{
                $data = json_decode($result, true);
            }catch(\Exception $e){
                $this->dump('parse error.', 2, $e);
            }
        }
        return $data;
    }

    /**
     * 用户注册
     */
    function register(){
        $data  = $this->check(array('username', 'password', 'code', 'nickname', 'qqnumber', 'phone',
            'realname', 'uuid'));
        $data['uuid'] = md5($data['uuid']);
        if(empty($data['username'])){
            $this->dump('用户名不能为空.');
        }
        if(empty($data['password'])){
            $this->dump('密码不能为空.');
        }
        if(empty($data['code'])){
            $this->dump('邀请码不能为空.');
        }
        $result = $this->connect('user/register', $data);
        if($result['code'] == 1){
            /*//这里因为注册返回的是大写UUID要统一一下...
            $result['data']['uuid'] = $result['data']['UUID'];
            Session::set('user_info', $result['data']);*/
            $this->dump('ok', 1);
        }else{
            $this->dump($result['msg']);
        }
    }

    /**
     * 用户登陆
     */
    function login(){
        $data  = $this->check(array('username', 'password', 'uuid'));
        $data['uuid'] = md5($data['uuid']);
        if(empty($data['username'])){
            $this->dump('用户名不能为空.');
        }
        if(empty($data['password'])){
            $this->dump('密码不能为空.');
        }
        $result = $this->connect('user/login', $data);
        if($result['code'] == 1){
            Session::set('user_info', $result['data']);
            $this->dump('ok', 1, $result['data']);
        }else{
            $this->dump($result['msg']);
        }
    }

    /**
     * 请求服务器数据
     */
    function request(){
        $data  = $this->check(array('action', 'params'));
        exit(json_encode($this->connect($data['action'], $data['params'])));
    }

    /**
     * 上传头像
     */
    function uploadFace(){
        $file = request()->file('file')->getInfo();
        if($file){
            $upload = array(
                'get_name'  => 'file',
                'type'  =>  $file['type'],
                'name'  =>  $file['name'],
                'file'  =>  $file['tmp_name'],
            );
            $result = $this->connect('user/face',
                array('username'  => input('username')), 'POST', $upload);
            if($result['code'] == 1){
                $line = session('user_info');
                $line['face'] = $result['data']['src'];
                session('user_info', $line);    //更新session face
            }
            exit(json_encode($result));
        }else{
            $this->dump('上传图片失败#1');
        }
    }

    /**
     * 修改用户信息（需要更新session）
     */
    function updateInfo(){
        $nickname = input('nickname');
        $user = Session::get('user_info');
        $data = array('username'=>$user['username'], 'nickname'=>$nickname);
        $result = $this->connect('user/update', $data);
        if($result['code'] == 1){
            $info = $this->connect('user/info', array('username'=>$user['username']));
            session('user_info', array_shift($info['data']));       //更新session
        }
        exit(json_encode($result));
    }

    /**
     * 用户退出
     */
    function logout(){
        Session::set('user_info', null);
        $this->dump('ok', 1);
    }

    /**
     * 获取用户信息
     */
    function info(){
        $info = Session::get('user_info');
        if($info){
            $info['hx_name'] = $info['username'];
            $info['hx_pass'] = md5("{$info['username']}_huoyanniao");        //返回16的MD5
            $this->dump('ok', 1, $info);
        }else{
            $this->dump('获取用户信息失败.');
        }
    }

    /**
     * 用户信息补全
     */
    function supData(){
        $name = input('name');
        if(empty($name)){
            $this->dump('请填写昵称');
        }
        $user = Session::get('user_info')['username'];
        $file = $_FILES['pic'];
        if(!$file){ $this->dump('请上传图片'); }
        if($file){
            $upload = array(
                'get_name'  => 'file',
                'type'  =>  $file['type'],
                'name'  =>  $file['name'],
                'file'  =>  $file['tmp_name'],
            );
            $result = $this->connect('user/face',
                array('username'  => $user), 'POST', $upload);
            if($result['code'] == 1){
                $up_nick = $this->connect('user/update', array('username'=>$user, 'nickname'=>$name));
                if($up_nick['code'] == 1){
                    $line = session('user_info');
                    $line['face'] = $result['data']['src'];
                    $line['nickname'] = $name;
                    session('user_info', $line);    //更新session
                    $this->dump('ok', 1);
                }else{
                    $this->dump('修改用户信息失败');
                }
            }else{
                $this->dump('修改用户头像失败');
            }
        }else{
            $this->dump('上传图片失败#1');
        }
    }

}
